﻿using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace DrawLibrary.Adorners
{
    public class PlaceholderAdorner : Adorner
    {
        public PlaceholderAdorner(TextBox adornedElement) : base(adornedElement)
        {
            this.IsHitTestVisible = false; //使水印不捕获事件

            adornedElement.TextChanged += MTextChange;
        }
        /// <summary>
        /// 上一次的输入框文本是否为空
        /// </summary>
        private bool PreIsEmpty = true;
        private void MTextChange(object sender, TextChangedEventArgs e)
        {
            var textBox = sender as TextBox;
            if (textBox == null)
            {
                return;
            }
            if (string.IsNullOrEmpty(textBox.Text))
            {
                _text = _drawText;
                this.InvalidateVisual(); // 强制刷新Adorner
                PreIsEmpty = true;
            }
            else
            {
                if (PreIsEmpty)
                {
                    _text = "";
                    this.InvalidateVisual(); // 强制刷新Adorner
                    PreIsEmpty = false;
                }
            }
        }

        private string _text;
        string _drawText;
        public PlaceholderAdorner(TextBox adornedElement, string text) : this(adornedElement)
        {
            _drawText = _text = text;
            MTextChange(adornedElement, null);
        }
        protected override void OnRender(DrawingContext dc)
        {
            base.OnRender(dc);
            // 创建一个格式化文本对象  
            FormattedText formattedText = new FormattedText(
                _text, // 文本内容  
                CultureInfo.CurrentCulture, // 使用的区域文化信息  
                FlowDirection.LeftToRight, // 文本流的方向  
                new Typeface("Arial"), // 字体  
                13, // 字体大小  
                Brushes.Gray, // 画笔颜色  
                0.01
            );


            // 使用DrawingContext的DrawText方法绘制文本  
            dc.DrawText(formattedText, new Point(0, 0));
        }
    }
}
